// RGB\HSL\HEX颜色转换
// RGB：R=0~255，G=0~255，B=0~255
// HSL：H=0~1，S=0~1，L=0~1
// HEX：6位十六进制数
// TODO HSL => RGB
function hslToRgb(hue, saturation, lightness) {
    var red, green, blue;
 
    if (saturation === 0) {
        red = green = blue = lightness; // achromatic
    } else {
        var hueToRgb = function hueToRgb(p, q, t) {
            if (t < 0) t += 1;
            if (t > 1) t -= 1;
            if (t < 1 / 6) return p + (q - p) * 6 * t;
            if (t < 1 / 2) return q;
            if (t < 2 / 3) return p + (q - p) * (2 / 3 - t) * 6;
 
            return p;
        };
 
        var q = lightness < 0.5 ? lightness * (1 + saturation) : lightness + saturation - lightness * saturation;
        var p = 2 * lightness - q;
 
        red = hueToRgb(p, q, h + 1 / 3);
        green = hueToRgb(p, q, h);
        blue = hueToRgb(p, q, h - 1 / 3);
    }
 
    return [Math.round(red * 255), Math.round(green * 255), Math.round(blue * 255)];
}
 
// TODO RGB => HSL
function rgbToHsl(red, green, blue) {
    red /= 255;
    green /= 255;
    blue /= 255;
 
    var max = Math.max(red, green, blue);
    var min = Math.min(red, green, blue);
    var hue, saturation, lightness = (max + min) / 2;
 
    if (max === min) {
        hue = saturation = 0; // achromatic
    } else {
        var d = max - min;
 
        saturation = lightness > 0.5 ? d / (2 - max - min) : d / (max + min);
 
        switch (max) {
            case red:
                hue = (green - blue) / d + (green < blue ? 6 : 0);
                break;
            case green:
                hue = (blue - red) / d + 2;
                break;
            case blue:
                hue = (red - green) / d + 4;
                break;
        }
 
        hue /= 6;
    }
 
    return [Math.floor(hue * 100), Math.round(saturation * 100) + "%", Math.round(lightness * 100) + "%"];
}
 
// TODO RGB => HEX
function rgbToHex(r, g, b) {
    return "#" + ((1 << 24) + (r << 16) + (g << 8) + b).toString(16).slice(1);
}
 
// TODO HEX => RGB
function hexToRgb(hex) {
    var result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
    return result ? {
        red: parseInt(result[1], 16),
        green: parseInt(result[2], 16),
        blue: parseInt(result[3], 16)
    } : null;
}

export function hexToHsl(hex){
	let rgb = hexToRgb(hex);
	return rgbToHsl(rgb.red,rgb.green,rgb.blue);
}

export function hexToHslString(hex){
	let hsl = hexToHsl(hex);
	return 'hsl(' + hsl[0] + ',' + hsl[1] + ',' + hsl[2] + ')';
}